package com.kaesar.leetcode.LeetCode_051_100;

import com.kaesar.leetcode.ListNode;

public class LeetCode_061 {
    public static ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode cur = head;
        // 链表的长度
        int length = 0;
        while (cur != null) {
            length++;
            cur = cur.next;
        }
        // 需要将倒数 toJump 位挪到 head 节点前面
        int toJump = k % length;
        if (toJump == 0) {
            return head;
        }
        ListNode first = head, last = head;
        while (toJump > 0) {
            last = last.next;
            toJump--;
        }
        while (last.next != null) {
            first = first.next;
            last = last.next;
        }
        ListNode newHead = first.next;
        first.next = null;
        last.next = head;
        return newHead;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        head.next = new ListNode(1);
        head.next.next = new ListNode(2);

        ListNode listNode = rotateRight(head, 4);
        while (listNode != null) {
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }
    }
}
